﻿using System;
using System.Web.Mvc;
using Atomic.Permission.BLL;
using Atomic.Common;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using Newtonsoft.Json;
using Atomic.Permission.Entities;
using Spring.Context;
using Spring.Context.Support;
using Atomic.Permission;

namespace Atomic.WebApp.Controllers
{
    public class PermissionController : Controller
    {
        static IApplicationContext context = null;

        static PermissionController()
        {
            try
            {
                context = ContextRegistry.GetContext("Atomic.Permission");
            }
            catch (Exception e)
            {
                throw e;
            }
        }

        //
        // GET: /Permission/

        #region 角色

        public ActionResult RoleIndex()
        {
            return View();
        }

        public JsonResult RolePage()
        {
            IRole roleBll = (IRole)context.GetObject("Role");
            Pager<RoleEntity> p1 = roleBll.GetPager(new Pager()
            {
                Index = Convert.ToInt32(Request["page"]),
                Rows = Convert.ToInt32(Request["rows"])
            });
            return this.Json(new
            {
                total = p1.Total,
                rows = p1.Records
            });
        }

        public JsonResult RoleAddOrUpdate(RoleEntity entity)
        {
            if (ModelState.IsValid)
            {
                IRole roleBll = (IRole)context.GetObject("Role");
                if (entity.ID == 0)
                {
                    roleBll.Add(entity);
                }
                else
                {
                    roleBll.Update(entity, entity.ID);
                }
                return this.Json(new
                {
                    Success = true
                });
            }
            else
            {
                return this.Json(new
                {
                    Success = false
                });
            }
        }

        public JsonResult RoleRemove()
        {
            IRole roleBll = (IRole)context.GetObject("Role");
            if (roleBll.Remove(Convert.ToInt32(Request["id"])))
            {
                return this.Json(new
                {
                    Success = true
                });
            }
            else
            {
                return this.Json(new
                {
                    Success = false
                });
            }
        }

        #endregion

        #region 窗体

        public ActionResult FunPointIndex()
        {
            return View();
        }

        public JsonResult FunPointTree()
        {
            int id = string.IsNullOrEmpty(Request["id"]) ? 0 : Convert.ToInt32(Request["id"]);
            IForm formBll = (IForm)context.GetObject("Form");
            List<FormEntity> list = formBll.GetChildren(id);
            return this.Json(list);
        }

        public JsonResult FunPointAddOrUpdate(FormEntity m)
        {
            if (ModelState.IsValid)
            {
                IForm formBll = (IForm)context.GetObject("Form");
                if (m.ID == 0)
                {
                    formBll.Add(m);
                }
                else
                {
                    formBll.Update(m, m.ID);
                }
                return this.Json(new
                {
                    Success = true,
                    Entity = m
                });
            }
            else
            {
                return this.Json(new
                {
                    Success = false
                });
            }
        }

        public JsonResult FunPointRemove()
        {
            IForm formBll = (IForm)context.GetObject("Form");
            if (formBll.Remove(Convert.ToInt32(Request["id"])))
            {
                return this.Json(new
                {
                    Success = true
                });
            }
            else
            {
                return this.Json(new
                {
                    Success = false
                });
            }
        }

        /// <summary>
        /// 子页面及操作点列表（不包含关闭的功能点）
        /// </summary>
        /// <returns></returns>
        public JsonResult FunPointsOperates()
        {
            int id = string.IsNullOrEmpty(Request["id"]) ? 0 : Convert.ToInt32(Request["id"]);  //上级功能点ID
            IForm formBll = (IForm)context.GetObject("Form");
            IList<FormEntity> funPoints = formBll.GetPager(null, m => m.PID == id && m.Enabled == true).Records;  //所有开启的功能点
            //List<FunPointDbEntity> funPoints = mgr.GetFunPoints(null, m => m.PID == id && m.Enabled == true).Records;  //所有开启的功能点
            //List<FunPointEntity> operations = mgr.GetOperatePoints(m => m.Enabled == true);   //所有功能点及专属功能点
            IList<FunPointEntity> operations = new FunPointBLL().GetList(m => m.Enabled);
            for (int i = 0; i < funPoints.Count; i++)
            {
                funPoints[i].FunPoints = operations.Where(m => m.FormID == funPoints[i].ID).ToList<FunPointEntity>();
            }
            return this.Json(funPoints);
        }

        #endregion

        #region 功能点
        public ActionResult OperatePointIndex()
        {
            return View();
        }

        public JsonResult OperatePointList()
        {
            IFunPoint fpBll = (IFunPoint)context.GetObject("FunPoint");
            List<FunPointEntity> list = fpBll.GetList(null);
            return this.Json(new
            {
                total = list.Count,
                rows = list
            });
        }

        public JsonResult OperatePointAddOrUpdate(FunPointEntity m)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    IFunPoint fpBll = (IFunPoint)context.GetObject("FunPoint");
                    if (m.ID == 0)
                    {
                        fpBll.Add(m);
                    }
                    else
                    {
                        fpBll.Update(m, m.ID);
                    }
                    return this.Json(new
                    {
                        Success = true,
                        Entity = m
                    });
                }
                else
                {
                    return this.Json(new
                    {
                        Success = false
                    });
                }
            }
            catch (Exception ex)
            {
                return this.Json(new
                {
                    Success = false,
                    Message = "系统错误"
                });
            }
        }

        public JsonResult OperatePointRemove()
        {
            IFunPoint fpBll = (IFunPoint)context.GetObject("FunPoint");
            try
            {
                fpBll.Remove(Convert.ToInt32(Request["id"]));
                return this.Json(new { Success = true });
            }
            catch (Exception ex)
            {
                return this.Json(new
                {
                    Success = false,
                    Message = "系统错误"
                });
            }
        }

        public ActionResult OperatePointAddOrUpdateControl()
        {
            return View();
        }
        #endregion

        #region 角色功能点权限

        /// <summary>
        /// 角色所有的功能的操作点关联
        /// </summary>
        /// <returns></returns>
        public JsonResult RoleFunOperateRelations()
        {
            int roleID = string.IsNullOrEmpty(Request["roleID"]) ? 0 : Convert.ToInt32(Request["roleID"]);
            IRoleFormFun rffBll = (IRoleFormFun)context.GetObject("RoleFormFun");
            List<RoleFormFunEntity> dbFunOprs = rffBll.GetList(m => m.RoleID == roleID).ToList();    //角色的功能/操作点关系
            return this.Json(dbFunOprs);
        }

        /// <summary>
        /// 更新或添加角色可用的功能/操作
        /// </summary>
        /// <returns></returns>
        public JsonResult RoleFunOperateRelationsAddOrUpdate()
        {
            try
            {
                int roleID = string.IsNullOrEmpty(Request["roleID"]) ? 0 : Convert.ToInt32(Request["roleID"]);
                if (roleID != 0)
                {
                    string data = Request["data"];
                    List<RoleFormFunEntity> list = JsonConvert.DeserializeObject<List<RoleFormFunEntity>>(data);
                    IRoleFormFun rffBll = (IRoleFormFun)context.GetObject("RoleFormFun");
                    for (int i = 0; i < list.Count; i++)
                    {
                        list[i].RoleID = roleID;
                        rffBll.Add(list[i]);
                    }
                    return this.Json(new
                    {
                        Success = true
                    });
                }
                else
                {
                    return this.Json(new
                    {
                        Success = false,
                        Message = "角色ID为0"
                    });
                }
            }
            catch (Exception ex)
            {
                return this.Json(new
                {
                    Success = false,
                    Message = ex.Message
                });
            }
        }
        
        #endregion

    }
}
